package com.hl.card.modular.packBack.controller;

import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.util.JAXBSource;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.hl.card.common.persistence.model.Goods;
import com.hl.card.common.remote.user.RemoteUser;
import com.hl.card.common.remote.user.RemoteUserService;
import com.hl.card.common.util.ResponseObject;
import com.hl.card.modular.pack.service.UserDataService;
import com.hl.card.modular.packBack.service.GoodsSevice;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.plugins.Page;
import com.hl.card.common.constant.factory.PageFactory;
import com.hl.card.common.controller.BaseController;
import com.hl.card.common.persistence.dao.UserMapper;
import com.hl.card.common.persistence.model.CommunityUser;
import com.hl.card.common.persistence.model.DisMemberApply;
import com.hl.card.common.persistence.model.User;
import com.hl.card.common.util.DateUtils;
import com.hl.card.common.util.PhoneFormatCheckUtils;
import com.hl.card.core.shiro.ShiroKit;
import com.hl.card.modular.packBack.service.CommunityUserService;

import scala.collection.generic.BitOperations;

/**
 * 社区管理员控制器
 * 
 * @author 袁伟
 *
 */
@Controller
@RequestMapping("/communityUser")
public class CommunityUserController extends BaseController {
	@Autowired
	private UserDataService userDataService;
	@Autowired
	private RemoteUserService remoteUserService;
	@Resource
	private GoodsSevice goodsSevice;
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private CommunityUserService communityUserService;
	private String PREFIX = "/packback/community_user/";

	/**
	 * 跳转社区管理员列表
	 * 
	 * @return
	 */
	@RequestMapping("/index")
	public String index() {
		return PREFIX + "community_user.html";
	}

	@RequestMapping("/excelList")
	public String excelList() {
		return PREFIX + "community_user_add.html";
	}

	/**
	 * 读取excel文件
	 *
	 * @param in
	 * @param
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uploadReport")
	@ResponseBody
	public Object uploadReport(MultipartFile upfile, HttpServletRequest request)
			throws Exception {
		String salt= ShiroKit.getRandomSalt(5);
		// 创建Excel工作薄
		// Goods goods = goodsSevice.selectByCode("CPTY");
		String curr = "CPTY008";
		if (upfile == null) {
			return super.FailuerTip("请选择上传的excel文件！");
		}
		Workbook work = getWorkbook(upfile.getInputStream());
		if (null == work) {
			return super.FailuerTip("Excel工作薄不能为空！");
		}
		Sheet sheet = null;
		Row row = null;
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		sheet = work.getSheetAt(0);
		if (sheet == null) {
			return super.FailuerTip("Excel的Shell不能为空！");
		}
		Integer id = ShiroKit.getUser().getId();
		request.getSession().setAttribute("upload_total_count" + id,
				sheet.getLastRowNum());
		// 遍历当前sheet中的所有行
		for (int j = 1; j <= sheet.getLastRowNum(); j++) {
			request.getSession().setAttribute("upload_count" + id, j);
			row = sheet.getRow(j);
			if (row == null) {
				continue;
			}
			try {
				String phone = getCellValue(row.getCell(0));
				if (StringUtils.isEmpty(phone)) {
					throw new Exception("手机号码为空");
				}
				if (!PhoneFormatCheckUtils.isMobileNO(phone)) {
					throw new Exception("手机号码格式错误");
				}
				User user = userMapper.selectByPhone(phone);
				if (user != null) {
					CommunityUser communityUser = communityUserService
							.findByUserId(user.getUserId());
					if (communityUser != null) {
						throw new Exception("该用户已经成为社区管理员,请勿重复申请");
					}
					communityUserService.add(user.getUserId());
					String countStr = getCellValue(row.getCell(1));
					int count = 1;
					if (StringUtils.isNotBlank(countStr)) {
						count = Integer.parseInt(countStr);
					}
					String info = stringRedisTemplate.opsForValue().get(curr);
					JSONObject obj;
					if (StringUtils.isBlank(info)) {
						obj = new JSONObject();
					} else {
						obj = JSONObject.parseObject(info);
					}
					obj.put(phone, Integer.toString(count*160));
					stringRedisTemplate.opsForValue().set(curr, obj.toJSONString());
				}else {
					User newUser;
					RemoteUser remoteUser = null;
					JSONObject json = remoteUserService.findSsoUserByPhone(phone);
					System.out.println(json.toJSONString());
					if (json.get("code").equals("0")) {
						JSONObject userObj= (JSONObject) json.get("user");
						if(userObj != null) {
							remoteUser = JSON.parseObject(userObj.toJSONString(),RemoteUser.class);
						}
					}
					//对无卡包用户的情况进行补充初始化
					if(remoteUser != null) {
						RemoteUser newRemoteUser=new RemoteUser();
						newRemoteUser.setLoginAccount(remoteUser.getMobilePhone());
						newRemoteUser.setMobilePhone(remoteUser.getMobilePhone());
						String userid=remoteUser.getUserId();
						newRemoteUser.setUserId(userid);
						newUser=new User();
						newUser=userDataService.ssouserToCarPackUser(newRemoteUser,newUser);
						newUser.setSalt(salt);
						userDataService.insert(newUser);

						if(newUser != null) {
							CommunityUser communityUser= communityUserService.findByUserId(user.getUserId());
							if(communityUser!=null)
							{
								throw new Exception("该用户已经成为社区管理员,请勿重复申请");
							}
							communityUserService.add(user.getUserId());
							String countStr = getCellValue(row.getCell(1));
							int count = 1;
							if(StringUtils.isNotBlank(countStr)) {
								count = Integer.parseInt(countStr);
							}
							String info = stringRedisTemplate.opsForValue().get(curr);
							JSONObject obj;
							if(StringUtils.isBlank(info)) {
								obj = new JSONObject();
							}else {
								obj = JSONObject.parseObject(info);
							}
							obj.put(phone, Integer.toString(count*160));
							stringRedisTemplate.opsForValue().set(curr, obj.toJSONString());
						}else {
							throw new Exception("尝试自动初始化卡包用户失败,请管理员核查");
						}
					}else {
						throw new Exception("没有会员账号无法成为社区管理员,请先注册成为普通会员");
					}
				}
			} catch (Exception ex) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("row", j);
				map.put("error", ex.getMessage());
				list.add(map);
				if (StringUtils.isEmpty(ex.getMessage())) {
					ex.printStackTrace();
				}

			}
		}
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("code", 200);
		result.put("data", list);
		result.put("message", "操作成功!");
		return result;
	}

	/**
	 *
	 * @param inStr
	 * @return
	 * @throws Exception
	 */
	public static Workbook getWorkbook(InputStream inStr) throws Exception {
		Workbook wb = null;
		wb = WorkbookFactory.create(inStr);
		return wb;
	}

	private String getCellValue(Cell cell) {
		String result = new String();
		switch (cell.getCellType()) {
		case HSSFCell.CELL_TYPE_NUMERIC:// 数字类型
			if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式
				SimpleDateFormat sdf = null;
				if (cell.getCellStyle().getDataFormat() == HSSFDataFormat
						.getBuiltinFormat("h:mm")) {
					sdf = new SimpleDateFormat("HH:mm");
				} else {// 日期
					sdf = new SimpleDateFormat("yyyy-MM-dd");
				}
				Date date = cell.getDateCellValue();
				result = sdf.format(date);
			} else if (cell.getCellStyle().getDataFormat() == 58) {
				// 处理自定义日期格式：m月d日(通过判断单元格的格式id解决，id的值是58)
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				double value = cell.getNumericCellValue();
				Date date = org.apache.poi.ss.usermodel.DateUtil
						.getJavaDate(value);
				result = sdf.format(date);
			} else {
				double value = cell.getNumericCellValue();
				CellStyle style = cell.getCellStyle();
				DecimalFormat format = new DecimalFormat();
				String temp = style.getDataFormatString();
				// 单元格设置成常规
				if (temp.equals("General")) {
					format.applyPattern("#");
				}
				result = format.format(value);
			}
			break;
		case HSSFCell.CELL_TYPE_STRING:// String类型
			result = cell.getRichStringCellValue().toString();
			break;
		case HSSFCell.CELL_TYPE_BLANK:
			result = "";
		default:
			result = "";
			break;
		}
		return result;
	}

	/**
	 * 查询列表
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping("/list")
	@ResponseBody
	public Object list(CommunityUser user, HttpServletRequest request) {
		String sort = request.getParameter("sort");
		String order = request.getParameter("order");
		Page<CommunityUser> page = new PageFactory<CommunityUser>()
				.defaultPage();
		List<CommunityUser> list = communityUserService.list(page, user, sort,
				order);
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("rows", list);
		result.put("total", page.getTotal());
		return result;
	}

	/**
	 * 导出
	 */
	@RequestMapping(value = "/exportExcel")
	@ResponseBody
	public void exportExcel(HttpServletResponse response) {
		List<Map<String,Object>> list=communityUserService.exportExcel();
		// 声明一个头部信息
		List<String> headers = Arrays.asList("用户账号", "邀请上限数", "状态");
		List<String> header_cloums = Arrays.asList("account", "invite_user_max_count", "status");
		// 声明一个工作薄
		HSSFWorkbook workbook = new HSSFWorkbook();
		// 生成一个表格
		HSSFSheet sheet = workbook.createSheet();
		sheet.setDefaultColumnWidth((short) 24);
		HSSFCellStyle style = workbook.createCellStyle();
		style.setBorderBottom(BorderStyle.THIN); // 下边框
		style.setBorderLeft(BorderStyle.THIN);// 左边框
		style.setBorderTop(BorderStyle.THIN);// 上边框
		style.setBorderRight(BorderStyle.THIN);// 右边框
		style.setAlignment(HorizontalAlignment.CENTER); // 居中
		style.setFillForegroundColor((short) 13);// 设置背景色
		style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

		HSSFCellStyle style2 = workbook.createCellStyle();
		style2.setBorderBottom(BorderStyle.THIN); // 下边框
		style2.setBorderLeft(BorderStyle.THIN);// 左边框
		style2.setBorderTop(BorderStyle.THIN);// 上边框
		style2.setBorderRight(BorderStyle.THIN);// 右边框
		style2.setAlignment(HorizontalAlignment.CENTER); // 居中
		HSSFRow row = sheet.createRow(0);

		for (String head : headers) {
			HSSFCell cell = row.createCell(headers.indexOf(head));
			HSSFRichTextString richString = new HSSFRichTextString(head);
			HSSFFont font3 = workbook.createFont();
			font3.setBold(true);
			richString.applyFont(font3);
			cell.setCellValue(richString);
			cell.setCellStyle(style);

		}
		for (int i = 0; i < list.size(); i++) {
			row = sheet.createRow(i + 1);
			for(int j=0;j<header_cloums.size();j++)
			{
				HSSFCell cell = row.createCell(j);
				String textValue="";
				if(header_cloums.get(j).equals("status"))
				{
					textValue=list.get(i).get(header_cloums.get(j))+"";
					if(textValue.equals("0"))
					{
						textValue="启用";
					}else
					{
						textValue="禁用";
					}
				}else{
				    textValue = list.get(i).get(header_cloums.get(j))+"";
				}
				HSSFRichTextString richString = new HSSFRichTextString(textValue.equals("null")?"":textValue);  
				cell.setCellValue(richString);
				cell.setCellStyle(style2);
			}
		}

		response.setContentType("application/octet-stream");
		try{
		response.setHeader("Content-disposition", "attachment;filename="
				+ new String(("社区管理员记录.xls").getBytes("UTF-8"), "ISO8859-1"));// 默认Excel名称
		response.flushBuffer();
		workbook.write(response.getOutputStream());
		}catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}

	/**
	 * 添加
	 * 
	 * @param phone
	 * @return
	 */
	@RequestMapping("/add")
	@ResponseBody
	public Object add(String phone) {
		if (StringUtils.isEmpty(phone)) {
			return super.FailuerTip("手机号不能为空");
		}
		String temp[] = phone.split("-");
		String phone_input = temp[0];
		if (!PhoneFormatCheckUtils.isMobileNO(phone_input)) {
			return super.FailuerTip("手机号码格式错误");
		}

		User user = userMapper.selectByPhone(phone_input);
		String curr = "CPTY008";
		if (user != null) {
			CommunityUser communityUser = communityUserService
					.findByUserId(user.getUserId());
			if (communityUser != null) {
				return super.FailuerTip("该用户已经成为社区管理员,请勿重复申请");
			}
			communityUserService.add(user.getUserId());
			int count = 1;
			if (temp.length == 2) {
				if (StringUtils.isNotBlank(temp[1])) {
					count = Integer.parseInt(temp[1]);
				}
			}

			String info = stringRedisTemplate.opsForValue().get(curr);
			JSONObject obj;
			if (StringUtils.isBlank(info)) {
				obj = new JSONObject();
			} else {
				obj = JSONObject.parseObject(info);
			}
			obj.put(phone_input, Integer.toString(count * 160));
			stringRedisTemplate.opsForValue().set(curr, obj.toJSONString());
			return super.SUCCESS_TIP;
		} else {
			return super.FailuerTip("没有会员账号无法成为社区管理员,请先注册成为普通会员");
		}

	}

	/**
	 * 批量修改
	 * 
	 * @param phone
	 * @return
	 */
	@RequestMapping("/updateBatch")
	@ResponseBody
	public Object updateBatch(
			@RequestParam(value = "ids[]") Integer[] ids,
			@RequestParam(value = "invite_user_max_counts[]") Integer[] invite_user_max_counts,
			@RequestParam(value = "community_codes[]") String[] community_codes) {
		communityUserService.updateBatch(ids, invite_user_max_counts,community_codes);
		return super.SUCCESS_TIP;
	}

	@RequestMapping("/switchStatus")
	@ResponseBody
	public Object switchStatus(Integer status, Integer id) {
		if (id == null) {
			return super.FailuerTip("ID不能为空");
		}
		if (status == null) {
			return super.FailuerTip("状态不能为空");
		}
		communityUserService.switchStatus(status, id);
		return super.SUCCESS_TIP;
	}

	@RequestMapping("/getUploadCount")
	@ResponseBody
	public Object getUploadCount(HttpServletRequest request) {
		Integer id = ShiroKit.getUser().getId();
		Integer count = request.getSession().getAttribute("upload_count" + id) == null ? 0
				: (Integer) request.getSession().getAttribute(
						"upload_count" + id);
		Integer total_count = request.getSession().getAttribute(
				"upload_total_count" + id) == null ? 0 : (Integer) request
				.getSession().getAttribute("upload_total_count" + id);
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("count", count);
		data.put("total_count", total_count);
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("code", 200);
		result.put("message", "操作成功");
		result.put("data", data);
		return result;
	}
}
